package com.fatdetection.demo.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.SyncReadListener;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fatdetection.demo.annotation.AuthAdmin;
import com.fatdetection.demo.annotation.AuthOperator;
import com.fatdetection.demo.annotation.AuthUser;
import com.fatdetection.demo.bean.LayuiTableRst;
import com.fatdetection.demo.bean.User;
import com.fatdetection.demo.bean.UserExcel;
import com.fatdetection.demo.service.UserService;
import com.fatdetection.demo.util.RstMsgUtils;
import com.fatdetection.demo.util.TokenUtils;
import com.fatdetection.demo.util.UploadUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/user")
@AuthAdmin
@AuthOperator
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    UploadUtils uploadUtils;
    @Autowired
    TokenUtils tokenUtils;

    @PostMapping("/login")
    public Object login(String phone, String password){
        User user = userService.login(phone, password);
        if(user == null){
            return RstMsgUtils.error("登录失败");
        } else {
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("username", user.getPhone());
            tokenMap.put("role", "0");
            String token = tokenUtils.geneToken(tokenMap);
            Map<String, Object> rstMap = new HashMap<>();
            rstMap.put("userInfo", user);
            rstMap.put("token", token);
            return RstMsgUtils.success(null, rstMap);
        }
    }

    @PostMapping("/addUserFromExcel")
    public Object addUserFromExcel(MultipartFile[] file){
        List<Object> rstData = new ArrayList<>();
        for (MultipartFile fil : file) {
            List<Object> objects = null;
            try {
                objects = EasyExcel.read(fil.getInputStream()
                        , UserExcel.class
                        , new SyncReadListener())
                        .sheet().doReadSync();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Map<String, Object> rst = userService.insertList(objects, fil.getOriginalFilename());
            rstData.add(rst);
        }
        return RstMsgUtils.success("用户导入详情", rstData);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页数", required = true),
            @ApiImplicitParam(name = "size", value = "每页的条目数", required = true),
            @ApiImplicitParam(name = "searchKey", value = "搜索的键（对应数据表字段，eg: username）", required = false),
            @ApiImplicitParam(name = "searchVal", value = "模糊搜索的值", required = false)
    })
    @GetMapping("/selectPage/{current}/{size}/{searchKey}/{searchVal}")
    public Object selectPage(@PathVariable Integer current
            , @PathVariable Integer size
            , @PathVariable String searchKey
            , @PathVariable String searchVal){
        Page<User> page = userService.selectAllPage(current, size, searchKey, searchVal);
        LayuiTableRst layuiTableRst = new LayuiTableRst();
        layuiTableRst.setCode(0);
        layuiTableRst.setCount((int) page.getTotal());
        layuiTableRst.setMsg("获取成功");
        layuiTableRst.setData(page.getRecords());
        return layuiTableRst;
    }
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true),
            @ApiImplicitParam(name = "phone", value = "手机号", required = true)
    })
    @PostMapping("/add")
    public Object insertUser(User user){
        if(user.getPhone() == null
        || user.getUsername() == null){
            return RstMsgUtils.error("userName/phone暂时必需");
        }
        int count = userService.insertUser(user);
        if(count == 1){
            return RstMsgUtils.success("注册成功", "");
        }else if(count == -2){
            return RstMsgUtils.error("该手机号已被注册");
        } else {
            return RstMsgUtils.error("注册失败");
        }
    }

    @PostMapping("/del")
    public Boolean delUser(String phone){
        return userService.delUser(phone);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "phone必需且暂时不支持修改", required = true),
    })
    @PostMapping("/update")
    public Boolean updateUser(User user){
        if(user.getPhone() == null){
            return false;
        }
        return userService.updateUser(user);
    }

    @GetMapping("/findAll")
    public List<User> findAll(){
        List<User> list = userService.findAll();
        return list;
    }

    @GetMapping("/findUserByGroup/{groupId}")
    public List<User> findUserByGroup(@PathVariable("groupId")Integer groupId){
        return userService.findUserByGroup(groupId);
    }

    @GetMapping("/findUserByGroupAndOrder/{groupId}")
    public List<User> findUserByGroupAndOrder(@PathVariable("groupId")Integer groupId){
        return userService.findUserByGroupAndOrder(groupId);
    }

    @GetMapping("/searchUser/{info}/{projectId}")
    public Object findUserByGroupAndOrder(@PathVariable("info")String info,
                                              @PathVariable Integer projectId){
        List<User> users = userService.searchUser(info, projectId);
        Map<String, Object> map = new HashMap<>();
        map.put("count", users.size());
        map.put("data", users);
        return map;
    }

    @GetMapping("/searchUser_1/{info}/{projectId}")
    public Object searchUserByPhoneAndName(@PathVariable("info")String info,
                                          @PathVariable Integer projectId){
        List<User> users = userService.searchUserByPhoneAndName(info, projectId);
        Map<String, Object> map = new HashMap<>();
        map.put("count", users.size());
        map.put("data", users);
        return map;
    }

    @GetMapping("/getUserByProj/{projectName}")
    public List<User> getUserByProj(@PathVariable("projectName")String projectName){
        return userService.findUserByProj(projectName);
    }

    @GetMapping("/getUserByPhone/{phone}")
    @AuthUser
    public User getUserByPhone(@PathVariable String phone){
        return userService.findUserByPhone(phone);
    }

    @GetMapping("/getUsersByProjectId/{projectId}")
    public List<User> getUsersByProjectId(@PathVariable("projectId") Integer projectId){
        List<User> list = userService.findUsersByProjectId(projectId);
        return list;
    }
}
